package com.weike.yuanding.configration;

import com.weike.yuanding.controller.UserController;
import com.weike.yuanding.entity.UserEntity;
import com.weike.yuanding.mapper.SessionMapper;
import com.weike.yuanding.mapper.UserMapper;
import com.weike.yuanding.vo.UserOnlineResVo;
import com.weike.yuanding.vo.UserSessionResVo;
import com.weike.yuanding.ws.WebsocketController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class RedisKeyExpirationListener implements MessageListener {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserController userController;


    @Autowired
    private WebsocketController websocketController;

    @Autowired
    private SessionMapper sessionMapper;

    private static final String USER_OLINE_KEY = "user:online:"; // 与你的常量保持一致

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = new String(message.getBody());

        if (expiredKey.startsWith(USER_OLINE_KEY)) {
            String userId = expiredKey.substring(USER_OLINE_KEY.length());
            handleUserOffline(userId);
        }
    }

    private void handleUserOffline(String userId) {
        // 实现你的业务逻辑
        System.out.println("用户ID: " + userId + " 已离线");
        UserEntity user = new UserEntity();
        user.setUserId(userId);
        user.setLastOlineTime(new Date());
        userMapper.updateById(user);

        UserOnlineResVo userOnlineResVo = new UserOnlineResVo();
        userOnlineResVo.setOnline(false);
        userOnlineResVo.setType(0);
        userOnlineResVo.setUserId(userId);
        try {
            List<UserSessionResVo> list = sessionMapper.selectListByUserId(userOnlineResVo.getUserId());
            list.forEach(item -> {
                if (item.getUserId() != null) {
                    userOnlineResVo.setAvatar(item.getDisplayAvatar());
                    userOnlineResVo.setName(item.getDisplayName());
                    websocketController.sendOnline(userOnlineResVo , item.getUserId());
                }
            });
        } catch (Exception e) {
            System.err.println("异步保存消息记录失败");
        }
    }
}